<template>
  <div v-loading="loading" element-loading-text="loading..." element-loading-spinner="el-icon-loading" class="dataForm fileForm">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row v-if="form.parentId !== '0' && form.parentId !== 'main' && parentFolderData.belong !== 'personal_files' && form.parentId !== undefined && form.parentId !== null && form.parentId !== '' && form.isBuiltIn !== '1'">
        <div>
          <el-col :span="24">
            <el-form-item :label="$t('父级文件夹')" prop="parentId">
              <treeselect
                ref="folderCETree"
                v-model="form.parentId"
                :options="folderOption"
                :flat="true"
                :show-count="true"
                :load-options="loadOptions"
                :default-expand-level="0"
                :open-delay="true"
                open-on-click
                :clearable="false"
                :branch-nodes-first="false"
                :placeholder="$t('请选择')"
              >
                <label slot="option-label" slot-scope="{ node, labelClassName }" :class="labelClassName">
                  {{ $t(node.label) }}
                </label>
                <label slot="value-label" slot-scope="{ node }">
                  {{ $t(node.label) }}
                </label>
              </treeselect>
            </el-form-item>
          </el-col>
        </div>
      </el-row>
      <el-row>
        <div>
          <el-col :span="24">
            <el-form-item :label="$t('文件夹名称')" prop="name">
              <el-input
                v-model="form.name"
                :maxlength="30"
                show-word-limit
                :placeholder="$t('文件夹名称')"
              />
            </el-form-item>
          </el-col>
        </div>
      </el-row>
      <el-row>
        <div>
          <el-col :span="24">
            <el-form-item :label="$t('排序')" prop="sort">
              <el-input
                v-model="form.sort"
                :placeholder="$t('排序')"
              />
            </el-form-item>
          </el-col>
        </div>
      </el-row>
      <el-row v-if="parentFolderData.belong !== 'personal_files'">
        <div class="area-header" style="margin-top: 15px;">
          <span class="area-header-title">
            {{ $t('权限配置') }}
            <el-tooltip placement="top">
              <div slot="content">
                <span style="color: white;">{{ $t('注: 当未配置权限时, 该目录不受权限控制, 但是父级目录配置过, 将会继承父目录的权限!') }}</span>
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <div v-if="copyOption" style="float: right;font-size: 13px;margin-top: 4px;">
            <span>{{ $t('已复制') + '"' + copyOption.dictLabel + '"' + $t('权限') }}</span>
            <div style="float: right;font-size: 18px;margin-top: -4px;margin-left: 10px;cursor: pointer;" @click="copyOption = undefined">×</div>
          </div>
        </div>
        <div>
          <el-table :data="form.permissionDictionary" class="nowrapTable formTable" border>
            <el-table-column :label="$t('权限类型')" align="center" min-width="90">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('权限类型') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'permissionDictionary.' + scope.$index + '.permission'" :rules="[{ required: true, message: $t('必填信息'), trigger: ['change'] }]">
                  <el-select v-model="scope.row.permission" disabled>
                    <el-option
                      v-for="(item, index) in permissionDictionaryOption"
                      :key="index"
                      :label="$t(item.dictLabel)"
                      :value="item.permission"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('用户')" align="center" min-width="120">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('用户') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'permissionDictionary.' + scope.$index + '.userIds'">
                  <UserSelect
                    v-model="scope.row.userIds"
                    :multiple="true"
                    :collapse-tags="detailShow"
                    :placeholder="$t('请选择')"
                    @change="resolveUpdateExceptions($event, scope.$index, 'user')"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('角色')" align="center" min-width="120">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('角色') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'permissionDictionary.' + scope.$index + '.rolesId'">
                  <el-select v-model="scope.row.rolesId" multiple clearable :collapse-tags="detailShow" :placeholder="$t('请选择')" @change="resolveUpdateExceptions($event, scope.$index, 'role')">
                    <el-option
                      v-for="item in selectRoleOptions"
                      :key="item.rolesId"
                      :label="$t(item.roleName)"
                      :value="item.roleId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!isEmpty(isShowTeamType)" align="center" min-width="120">
              <template slot="header" slot-scope="{}">
                <span>{{ $t(isShowTeamType === 'deal' ? '项目成员' : (isShowTeamType === 'fund' ? '基金成员' : '')) }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'permissionDictionary.' + scope.$index + '.teamIds'">
                  <el-select v-model="scope.row.teamIds" :multiple="true" :clearable="true" :collapse-tags="detailShow" :placeholder="$t('请选择')" filterable @change="resolveUpdateExceptions($event, scope.$index, 'team')">
                    <el-option
                      v-for="dict in (isShowTeamType === 'deal' ? dealTeamRoleOptions : (isShowTeamType === 'fund' ? fundTeamRoleOption : []))"
                      :key="dict.id"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" width="120">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('操作') }}</span>
                <el-button size="small" type="text" icon="el-icon-delete-solid" @click="oneClickClear()" />
                <el-tooltip placement="top">
                  <div slot="content">
                    {{ $t('按钮说明:') }} <br>
                    &nbsp;&nbsp;{{ $t('一键清空') }} ( <i class="el-icon-delete-solid" /> ): {{ $t('清空所有权限') }} <br>
                    &nbsp;&nbsp;{{ $t('复制') }} ( <i class="el-icon-document-copy" /> ): {{ $t('复制当前行') }}<br>
                    &nbsp;&nbsp;{{ $t('插入') }} ( <i class="el-icon-circle-plus-outline" /> ): {{ $t('将复制的行内容插入(补充)到当前行') }}<br>
                    &nbsp;&nbsp;{{ $t('替换') }} ( <i class="el-icon-edit-outline" /> ): {{ $t('将复制的行内容替换当前行') }}<br>
                    &nbsp;&nbsp;{{ $t('删除') }} ( <i class="el-icon-delete" /> ): {{ $t('清空当前行的权限') }}<br>
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-button size="small" type="text" icon="el-icon-document-copy" @click="copyPermission(scope.$index)" />
                <el-button size="small" type="text" icon="el-icon-circle-plus-outline" @click="insertPermission(scope.$index)" />
                <el-button size="small" type="text" icon="el-icon-edit-outline" @click="pastePermission(scope.$index)" />
                <el-button size="small" type="text" icon="el-icon-delete" @click="deletePermission(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-row>
    </el-form>
    <!--操作按钮-->
    <!--<div style="position: absolute;bottom: 5px;left: 0;">-->
    <!--  <span style="font-size: 13px;font-weight: bold;">{{ $t('显示详情') }}</span>-->
    <!--  <el-switch v-model="detailShow" active-color="#13ce66" inactive-color="#c7c7c7" />-->
    <!--</div>-->
    <div class="dialog-footer" style="text-align: right;">
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>
  </div>
</template>
<script>
import permissionList from '@/views/folder/folderRolePermission'
import Treeselect from '@riophae/vue-treeselect'
import userSelect from '@/components/UserSelect/index'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  saveFileDir,
  getFileFolder,
  fileClassTreeStructure,
  sqlGetParentFolderBySubId
} from '@/api/file/filefolder/folder.js'
import { getUser } from '@/api/system/user'
import { getArrayByCode } from '@/api/file/directoryRelatedBusiness/directoryRelatedBusiness'
export default {
  components: {
    Treeselect,
    userSelect
  },
  props: {
    businessId: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      loading: false,
      // 表单参数
      form: {
        permissionDictionary: []
      },
      // 默认权限
      permissionDictionaryOption: permissionList,
      // 角色下拉
      selectRoleOptions: [],
      // 表单校验
      rules: {
        name: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
        sort: [{ min: 0, max: 3, message: '请输入0-999', trigger: ['blur', 'change'] }]
      },
      parentFolderData: {
        belong: undefined
      },
      oneFolder: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      folderOption: [],
      // 目录归属
      businessType: undefined,
      // 展示项目团队成员还是基金团队成员
      isShowTeamType: undefined,
      // 复制的数据
      copyOption: undefined,
      // 团队成员字典
      dealTeamRoleOptions: [],
      // 基金成员字典
      fundTeamRoleOption: [],
      // 详细信息用户下拉开关
      detailShow: true,
      // 项目List页面会给这个参数传值
      dealBaseId: ''
    }
  },
  watch: {
    'form.sort': {
      handler(value) {
        if (value !== undefined && value !== '' && value !== null) {
          this.form.sort = value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '')
        }
      }
    },
    detailShow: {
      handler() {
        this.$forceUpdate()
      },
      deep: true
    }
  },
  mounted() {
  },
  created() {
    this.loadingRoleSelect()
    this.getDicts('deal_team_role').then(response => {
      this.dealTeamRoleOptions = []
      response.data && response.data.forEach(item => {
        this.dealTeamRoleOptions.push({ 'id': item.id, 'dictLabel': item.dictLabel, 'dictValue': ('deal-' + item.dictValue) })
      })
    })
    this.getDicts('fund_team_role').then(response => {
      this.fundTeamRoleOption = []
      response.data && response.data.forEach(item => {
        this.fundTeamRoleOption.push({ 'id': item.id, 'dictLabel': item.dictLabel, 'dictValue': ('fund-' + item.dictValue) })
      })
    })
  },
  methods: {
    // 初始化
    init(data) {
      this.oneFolder = false
      this.loading = true
      this.parentFolderData = data
      // 获取配置, 查看是否展示团队成员, 展示那种团队成员
      getArrayByCode('java_deal_and_fund_data_type').then(res => {
        if (res.data) {
          res.data.some(config => {
            if (config.busType.split(',').includes(this.businessType)) {
              this.isShowTeamType = config.busAlias
              return true
            }
          })
        }
        console.log('打开目录详情')
        // data.isNewFolder 是否为新增文件夹
        if (data.isNewFolder) {
          this.reset()
          this.form.parentId = data.id
          // 自动加载出下拉, 下拉回显
          this.dropdownEcho()
        } else {
          // 这里就打开文件夹编辑
          getFileFolder(data.id).then(response => {
            this.form = response.data
            this.dropdownEcho()
            const dataPermission = response.data.permissionDictionary
            this.form.permissionDictionary = JSON.parse(JSON.stringify(this.permissionDictionaryOption))
            console.log('还原权限到列表')
            if (!this.isEmpty(dataPermission)) {
              console.log(dataPermission)
              this.form.permissionDictionary.forEach(item => {
                dataPermission.forEach(item2 => {
                  if (item2.fileId === this.parentFolderData.id) {
                    Object.keys(item2).forEach(item3 => {
                      if (item.permission === item3 && item2[item3] === 'Y' && item2.type === 'user') {
                        if (this.isEmpty(item.userIds)) {
                          item.userIds = []
                        }
                        if (!item.userIds.includes(item2.userId)) {
                          item.userIds.push(item2.userId)
                        }
                      }
                      if (item.permission === item3 && item2[item3] === 'Y' && item2.type === 'role') {
                        if (this.isEmpty(item.rolesId)) {
                          item.rolesId = []
                        }
                        if (!item.rolesId.includes(item2.userId)) {
                          item.rolesId.push(item2.userId)
                        }
                      }
                      if (item.permission === item3 && item2[item3] === 'Y' && item2.type === 'team') {
                        if (this.isEmpty(item.teamIds)) {
                          item.teamIds = []
                        }
                        if (!item.teamIds.includes(item2.userId)) {
                          item.teamIds.push(item2.userId)
                        }
                      }
                    })
                  }
                })
              })
            }
            this.loading = false
          })
        }
      })
    },
    // 初始化树
    initTreeData(treeData, businessType) {
      this.folderOption = []
      console.log(businessType)
      this.businessType = businessType
      // 如果选择的是 股权项目..等目录, 就只展示对应的目录 其他不展示 否则群不展示
      const folderOne = treeData.find(obj => obj.id === this.businessType)
      if (folderOne) {
        this.folderOption.push(JSON.parse(JSON.stringify(folderOne)))
      } else {
        this.folderOption = JSON.parse(JSON.stringify(treeData))
      }
      this.checkIfItIsOptionalMain()
    },
    // 检查是否可选
    checkIfItIsOptionalMain() {
      this.folderOption.forEach(item => {
        item.isDisabled = item.id === this.parentFolderData.id
        this.checkIfItIsOptionalSub(item)
      })
    },
    checkIfItIsOptionalSub(data) {
      if (data !== undefined && data !== null && data.children !== undefined && data.children !== null) {
        data.children.forEach(item => {
          item.isDisabled = item.id === this.parentFolderData.id
          this.checkIfItIsOptionalSub(item)
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        belong: undefined,
        sort: undefined,
        permissionDictionary: JSON.parse(JSON.stringify(this.permissionDictionaryOption))
      }
      this.resetForm('form')
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.createFolderLoading = false
    },
    // 校验权限
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.parentFolderData.belong === 'personal_files') {
            this.submitFormStart()
          } else {
            this.submitFormStart()
          }
        }
      })
    },
    /** 提交按钮 */
    submitFormStart() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 新增一级目录 这个if-else 与二级目录无关
          if (this.parentFolderData.id === 'main') {
            this.parentFolderData.isNewFolder = false
            this.oneFolder = true
          } else {
            // 修改一级目录
            if (this.parentFolderData.parentId === '0' && this.parentFolderData.level === 0 && !this.parentFolderData.isNewFolder) {
              this.oneFolder = true
            }
          }
          this.loading = true
          // 新文件属于哪个类别
          this.form.belong = this.parentFolderData.belong
          this.loading = false
          this.saveData()
        }
      })
    },
    saveData() {
      this.loading = true
      // 处理一级目录新建时无法显示问题
      if (this.form.parentId === 'main') {
        this.form.parentId = '0'
      }
      this.form.businessId = this.$route.query.id === undefined ? (this.$route.query.lpId === undefined ? undefined : this.$route.query.lpId) : this.$route.query.id
      console.log('1111111111111111111111111')
      if (this.isEmpty(this.form.businessId)) {
        this.form.businessId = this.dealBaseId
      }
      saveFileDir(this.form).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          var subData = response.data
          subData.belong = this.parentFolderData.belong
          this.$forceUpdate()
          this.$emit('addToLeftFolderMenu', subData, this.parentFolderData, this.parentFolderData.isNewFolder, this.oneFolder)
        } else {
          this.msgError(response.msg)
        }
        this.reset()
        this.loading = true
        this.$parent.$parent.createFolderLoading = false
      })
    },
    // 加载 权限下拉
    loadingRoleSelect() {
      getUser().then(response => {
        this.selectRoleOptions = response.datas.roles
      })
    },
    loadOptions({ action, parentNode, callback }) {
      console.log(action, parentNode, callback)
      if (action === 'LOAD_CHILDREN_OPTIONS') {
        fileClassTreeStructure({ businessId: this.businessType, belong: parentNode.belong, parentId: parentNode.id }).then(response => {
          console.log(response)
          var data = response.data
          if (!this.isEmpty(data)) {
            parentNode.children = data
          } else {
            delete parentNode.children
            parentNode.hasChildren = false
          }
          callback()
        }).catch(() => {
          callback()
        })
      }
    },
    /**
     * 一键清空
     */
    oneClickClear() {
      this.form.permissionDictionary.forEach(item => {
        item.userIds = []
        item.rolesId = []
        item.teamIds = []
      })
      this.msgSuccess(this.$t('操作完成'))
    },
    /**
     * 设置值,解决修改select后, 页面不变化
     */
    resolveUpdateExceptions(value, index, type) {
      if (type === 'user') {
        this.$set(this.form.permissionDictionary[index], 'userIds', value)
      } else if (type === 'role') {
        this.$set(this.form.permissionDictionary[index], 'rolesId', value)
      } else if (type === 'team') {
        this.$set(this.form.permissionDictionary[index], 'teamIds', value)
      }
      this.overloadTable()
    },
    /**
     * 重载表格
     */
    overloadTable() {
      this.form.permissionDictionary = JSON.parse(JSON.stringify(this.form.permissionDictionary))
      this.$forceUpdate()
    },
    /**
     * 复制权限
     */
    copyPermission(index) {
      this.copyOption = JSON.parse(JSON.stringify(this.form.permissionDictionary[index]))
      this.msgSuccess(this.$t('操作完成'))
    },
    /**
     * 替换权限
     */
    pastePermission(index) {
      if (this.copyOption) {
        if (index) {
          this.form.permissionDictionary[index].userIds = this.copyOption.userIds
          this.form.permissionDictionary[index].rolesId = this.copyOption.rolesId
          this.form.permissionDictionary[index].teamIds = this.copyOption.teamIds
          this.overloadTable()
          this.msgSuccess(this.$t('操作完成'))
        }
      }
    },
    /**
     * 删除权限-当前行
     */
    deletePermission(index) {
      if (!this.isEmpty(index) || index === 0) {
        this.form.permissionDictionary[index].userIds = []
        this.form.permissionDictionary[index].rolesId = []
        this.form.permissionDictionary[index].teamIds = []
        this.overloadTable()
        this.msgSuccess(this.$t('操作完成'))
      }
      this.copyOption = undefined
    },
    /**
     * 插入权限
     */
    insertPermission(index) {
      if (this.copyOption) {
        if (index) {
          const arr = ['userIds', 'rolesId', 'teamIds']
          arr.forEach(key => {
            if (this.isEmpty(this.form.permissionDictionary[index][key])) {
              this.form.permissionDictionary[index][key] = []
            }
            if (this.copyOption[key]) {
              this.copyOption[key].forEach(item => {
                if (!this.form.permissionDictionary[index][key].includes(item)) {
                  this.form.permissionDictionary[index][key].push(item)
                }
              })
            }
          })
          this.overloadTable()
          this.msgSuccess(this.$t('操作完成'))
        }
      }
    },
    dropdownEcho() {
      if (this.form.parentId !== '0' && this.form.parentId !== 'main' && this.parentFolderData.belong !== 'personal_files' && this.form.parentId !== undefined && this.form.parentId !== null && this.form.parentId !== '' && this.form.isBuiltIn !== '1') {
        if (this.form.parentId) {
          sqlGetParentFolderBySubId({ parentId: this.form.parentId, belong: this.parentFolderData.belong, businessId: this.businessId }).then(response => {
            console.log('回显', response.data)
            if (response.data && response.data[0]) {
              this.folderOption && this.folderOption.forEach(item => {
                if (item.id === response.data[0].id) {
                  item.children = response.data[0].children
                  var node = this.$refs.folderCETree.getNode(item.id)
                  if (node) {
                    node.childNode = response.data[0].children
                    if (node.childNode != null) {
                      node.childNode.isDefaultExpanded = true
                    }
                  }
                }
              })
            }
          })
        }
      }
    }
  }
}
</script>
<style scoped>
#table1 tr th{
  background-color: #F6F7FB;
  line-height: 27px!important;
}
#table1 tr th,#table1 tr td{
  border: 1px solid #DFE6EC;
  text-align: center;
  font-size: 12px;
  padding: 0 20px;
  line-height: 25px;
}
#table1{
  border-collapse: collapse;
}
.el-form-item__label {
  display: block;
  text-align: left;
  width: auto !important;
  font-weight: normal !important;
}
.dataForm .el-row .el-form-item {
  min-height: 100%;
}
</style>
